/**
 * GetFileSizeUtil.java
 * 版权所有(C) 2013
 * 创建者:cuiran 2013-12-25 上午10:54:42
 */
package com.ghyf.mplay.net.ftp;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;

/**
 * 获取文件大小 
 * @author cuiran
 * @version 1.0.0
 */
public class GetFileSizeUtil {

	 private static GetFileSizeUtil instance;
	 
	 public GetFileSizeUtil()
	 {
	 
	 }
	 
	 public static GetFileSizeUtil getInstance()
	 {
		  if (instance == null)
		  {
		   instance = new GetFileSizeUtil();
		  }
		 return instance;
	 }
	 
	 
	 @SuppressWarnings("resource")
	public long getFileSizes(File f) throws Exception
	 {
		  long s = 0;
		  if (f.exists())
		  {
			   FileInputStream fis = null;
			   fis = new FileInputStream(f);
			   s = fis.available();
		  }
		  else
		  {
			   f.createNewFile();
			   System.out.println("文件不存在");
		  }
		  return s;
	 }
	 
	 long localSize = 0;
	 public long getFileSize(File f) throws Exception
	 {
	  
	  File flist[] = f.listFiles();
	  for (int i = 0; i < flist.length; i++)
	  {
		   if (flist[i].isDirectory())
		   {
			   localSize = localSize + getFileSize(flist[i]);
		   }
		   else
		   {
			   localSize = localSize + flist[i].length();
		   }
	  }
	  return localSize;
	 }
	 
	 
	 public String FormetFileSize(long fileS)
	 {// 转换文件大小
	  DecimalFormat df = new DecimalFormat("#.00");
	  String fileSizeString = "";
	  if (fileS < 1024)
	  {
	   fileSizeString = df.format((double) fileS) + "B";
	  }
	  else if (fileS < 1048576)
	   {
	    fileSizeString = df.format((double) fileS / 1024) + "K";
	   }
	   else if (fileS < 1073741824)
	   {
	    fileSizeString = df.format((double) fileS / 1048576) + "M";
	   }
	   else
	   {
	    fileSizeString = df.format((double) fileS / 1073741824) + "G";
	   }
	  return fileSizeString;
	 }
	 
	 
	 public long getlist(File f)
	 {// 递归求取目录文件个数
	  long size = 0;
	  File flist[] = f.listFiles();
	  size = flist.length;
	  for (int i = 0; i < flist.length; i++)
	  {
	   if (flist[i].isDirectory())
	   {
	    size = size + getlist(flist[i]);
	    size--;
	   }
	  }
	  return size;
	 }
	 
	}
